<template>
  <div>

    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.conferenceName" clearable placeholder="会议名称" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-input v-model="query.typeName" clearable placeholder="用户类型" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
        <!-- ✅ 导入导出按钮 -->
        <!-- <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button> -->
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column
          type="selection"
          width="55">
        </el-table-column> -->
        <el-table-column prop="conferences.conferenceName" label="会议名称"></el-table-column>
        <el-table-column prop="participantTypes.typeName" label="用户类型"></el-table-column>
        <el-table-column prop="feeAmount" label="费用"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.typeId,scope.row.conferenceId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
<el-dialog title="新增用户类型" :visible.sync="editVisible" width="30%">
  <el-form
    ref="form"
    :model="form"
    :rules="rules"
    label-width="100px"
  >
    <!-- 会议类型下拉，绑定 conferenceId，展示 conferenceName -->
    <!-- <el-form-item label="会议类型" prop="conferenceId">
      <el-select v-model="form.conferenceId" placeholder="请选择会议类型">
        <el-option
          v-for="item in conferences"
          :key="item.conferenceId"
          :label="item.conferenceName"
          :value="item.conferenceId"
        />
      </el-select>
    </el-form-item> -->

    <!-- 用户类型下拉，绑定 typeId，展示 typeName -->
    <!-- <el-form-item label="用户类型" prop="typeId">
      <el-select v-model="form.typeId" placeholder="请选择用户类型">
        <el-option
          v-for="item in participantTypes"
          :key="item.typeId"
          :label="item.typeName"
          :value="item.typeId"
        />
      </el-select>
    </el-form-item> -->

    <!-- 描述 -->
    <el-form-item label="费用" prop="feeAmount">
      <el-input
        v-model="form.feeAmount"
        placeholder="请输入费用"
      />
    </el-form-item>
  </el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="cancelEdit">取 消</el-button>
    <el-button type="primary" @click="saveEdit">确 定</el-button>
  </span>
</el-dialog>
    <!-- 新增弹出框 -->
    <el-dialog title="新增用户类型" :visible.sync="addVisible" width="30%">
      <el-form
        ref="form"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <!-- 会议类型下拉，绑定 conferenceId，展示 conferenceName -->
        <el-form-item label="会议类型" prop="conferenceId">
          <el-select v-model="addForm.conferenceId" placeholder="请选择会议类型">
            <el-option
              v-for="item in conferences"
              :key="item.conferenceId"
              :label="item.conferenceName"
              :value="item.conferenceId"
            />
          </el-select>
        </el-form-item>
      
        <!-- 用户类型下拉，绑定 typeId，展示 typeName -->
        <el-form-item label="用户类型" prop="typeId">
          <el-select v-model="addForm.typeId" placeholder="请选择用户类型">
            <el-option
              v-for="item in participantTypes"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
      
        <!-- 费用 -->
        <el-form-item label="费用" prop="feeAmount">
          <el-input
            v-model="addForm.feeAmount"
            placeholder="请输入费用"
          />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'
import dayjs from 'dayjs';


export default {
    name: 'basetable',
    data() {
      return {
        query: {
            conferenceName: '',
            typeName: '',
            pageIndex: 1,
            pageSize: 30
        },
        tableData: [],
        multipleSelection: [],
        exportData: [],
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        form: {
          typeName: '',
          description: ''
        },
        conferences:{},
        participantTypes:{},
        addForm: {
          typeId: null,
          conferenceId: null,
          feeAmount: ''
        },
        idx: -1,
        id: -1,
        rules: {
          conferenceId: [
            { required: true, message: '请选择会议类型', trigger: 'change' }
          ],
          typeId: [
            { required: true, message: '请选择用户类型', trigger: 'change' }
          ],
          feeAmount: [
            { required: true, message: '费用不能为空', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!/^\d+(\.\d{1,2})?$/.test(value)) {
                  callback(new Error('请输入合法的数字，最多保留两位小数'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ]
        }
      };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/conferenceTypeFees/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          typeName: this.query.typeName,
          conferenceName: this.query.conferenceName
        }).then(res=>{
          this.pageTotal = res.total,
          this.tableData = res.data
        });
        requests.get("/conferences/selectAll").then(res=>{
          this.conferences = res          
        })
        requests.get("/participantTypes/selectAll").then(res=>{
          this.participantTypes = res
        })
      },
      // 触发搜索按钮
      handleSearch() {
          this.query.pageIndex = 1;
          this.loading();
      },
      // 删除操作
      handleDelete(row,row2) {
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
        })
            .then(() => {
                requests.delete("/conferenceTypeFees/delById",{
                  typeId: row,
                  conferenceId: row2
                }).then(res=>{
                  this.$message.success(res);
                  this.loading()
                })
            })
      },
      // 编辑操作
      handleEdit(row) {
        // 安全深拷贝 row 对象，避免响应式污染
        const newForm = JSON.parse(JSON.stringify(row));
        // 赋值给表单
        this.form = newForm;
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.form.resetFields();
      },
      // 保存编辑
      saveEdit() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          // 校验成功，调用接口
          requests.post("/conferenceTypeFees/edit", this.form)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.editVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      // 单选、多选改变时调用
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的酒店');
          return;
        }
      
        this.$confirm(`确定删除这 ${this.multipleSelection.length} 项吗？`, '提示', {
          type: 'warning'
        })
          .then(() => {
            const ids = this.multipleSelection.map(item => item.typeId);
            requests.post('/participantTypes/delByIds', ids)  // ✅ 注意这里直接传数组
              .then(res => {
                this.$message.success(res);
                this.loading(); // 重新加载表格
              })
          })
      },
      //新增操作
      handleAdd(row) {
        this.addForm = row;
        this.addVisible = true;
      },
      // 取消操作
      cancelAdd() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.addForm.resetFields();
      },
      // 保存操作
      saveAdd() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          
          // // 校验成功，调用接口
          requests.post("/conferenceTypeFees/add", this.addForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.addVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
